package com.gitee.cui.basic.producerandconsumer;

import com.gitee.cui.petstore.actor.Consumer;
import com.gitee.cui.petstore.actor.Producer;
import com.gitee.cui.petstore.goods.Goods;
import com.gitee.cui.petstore.goods.IGoods;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程不安全宠物商店模拟类
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/19 14:40
 **/
public class NotSafePetStore {

    private static NotSafeDataBuffer<IGoods> notSafeDataBuffer = new NotSafeDataBuffer<>();

    private static Callable<IGoods> produceAction = () -> {
        // 首先生成一个随机商品
        IGoods goods = Goods.produceOne();
        // 将商品放到缓存区中
        try {
            notSafeDataBuffer.add(goods);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return goods;
    };

    private static Callable<IGoods> comsumerAction = () -> {
        // 从缓存区中取出一个商品
        IGoods goods = null;
        try {
            goods = notSafeDataBuffer.fetch();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return goods;
    };

    public static void main(String[] args) {
        System.setErr(System.out);

        // 同时并发执行的线程数
        final int THREAD_TOTAL = 20;
        // 线程池，用于多线程模拟测试
        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_TOTAL);
        for (int i = 0; i < 5; i++) {
            // 生产者每生产一个商品，间隔500毫秒
            executorService.submit(new Producer(produceAction, 500));
            // 消费者每消费一个商品，间隔1500毫秒
            executorService.submit(new Consumer(comsumerAction, 1500));
        }
    }
}
